package com.wavecoler.professor.dao;
import java.util.List;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;
import com.wavecoler.dao.PMF;
import com.wavecoler.professor.objects.Problem;
import com.wavecoler.professor.objects.Word;

public class WordDAO {

	private static final Logger log = Logger.getLogger(WordDAO.class.getName());
	
	public static void insertWord(Word word) {

		// LLamamos a la clase que tendra la persistencia
		PersistenceManager pm = null;
		// Haciendo la persistencia de datos
		pm = PMF.get().getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		try {
			tx.begin();
			pm.makePersistent(word);
			tx.commit();
			log.info("transaction commit");
		} catch (Exception e) {
			log.warning(e.getMessage());
		} finally {
			if (tx.isActive()) {
				tx.rollback();
				log.info("did transaction rollback");
				log.warning("did transaction rollback");
			}
			if (pm != null)
				pm.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public static List<String> getWords() {
		PersistenceManager pm = null;
		try {
			pm = PMF.get().getPersistenceManager();
			Query query = pm.newQuery("select mainWord from " + Word.class.getName()
					+ "");
			List<String> words = (List<String>) query.execute();
			words.size(); // es necesario agregarlo debido a bug -
							// http://www.atentia.net/2010/03/app-engine-and-jdo-object-manager-has-been-closed/
			return words;
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (pm != null)
				pm.close();
		}
    }
	
	 @SuppressWarnings("unchecked")
	 //Method to return the list of users

	public static List<Word> getWordList(){
	  PersistenceManager pm = null;
	  try { 
		  pm = PMF.get().getPersistenceManager();
	      Query query = pm.newQuery("select from "+Word.class.getName()+""); 
	      List<Word> words = (List<Word>) query.execute();
	      words.size();
	      return words;
	  } catch(Exception e){
			log.info(e.getMessage() + " -- "+e.getCause());
			throw new RuntimeException(e);
	  } finally {
		  if (pm != null) pm.close();
	  }
	 }
	
}
